<template>
  <view class="menu-container">
    <eui-text type="name" :value="title" class="title"></eui-text>
    <eui-grid :column="4" :showBorder="false" :highlight="false" :square="false">
      <eui-grid-item v-for="item in columnList" :key="item.c_mdcode" class="grid-item-class">
        <view class="grid-item-box" style="background-color: #fff;"
          @touchstart="startLongPress(item.c_mdcode)"
          @touchend="endLongPress"
          @touchcancel="endLongPress"
          @click="onClickMenu(item)"
        >
          <view class="img-box flex-row-center" :style="{'background': item.c_start_color}">
            <image :src="item.c_menu_img" mode="scaleToFill" class="image" @error="imageError(item)"/>
          </view>
          <text class="text ellipsis-line-2">{{ item.c_title }}</text>
        </view>
      </eui-grid-item>
      <eui-grid-item @click="onClickAddMenu" v-if="columnList.length < 8">
        <view class="grid-item-box flex-row-center" style="background-color: #fff;">
          <view class="img-box">
            <image src="@/static/img/homeImgs/home_manage.png" mode="scaleToFill" class="last-image" />
          </view>
          <text class="text last-grid-text">管理</text>
        </view>
      </eui-grid-item>
    </eui-grid>
  </view>
</template>

<script setup lang="ts">
import {  ref, onMounted, watch, onUnmounted } from 'vue';
import { onLoad, onShow } from "@dcloudio/uni-app";
import service from '@/common/service';
import { useMainStore } from '../../../store/modules/store';
const mainStore = useMainStore();
const { loginInfo } = mainStore;
import { useLoginStore } from '@/store/modules/useLoginStore';
const LoginStore = useLoginStore();
import { hexToRgbToLinear } from '@/hooks/useUtils';
import { useRefreshStore } from '@/store/useRefreshStore';
import eventBus from '@/pages/MainViews/eventBus';

/**
 *  HomeMenuComponent 导航菜单
 */

const title = ref('常用功能');


/**
 * 获取常用菜单
 */
type Menu = {
  c_client_type: 'string',
  c_end_color: 'string',
  c_ini_param: 'string',
  c_limitcode: 'string',
  c_md_name: 'string',
  c_mdcode: 'string',
  c_menu_img: 'string',
  c_name: 'string',
  c_origin_type: 'string',
  c_start_color: 'string',
  c_system: 'string',
  c_title: 'string',
}
const columnList = ref<Menu[]>([]);
const baseUrl = '../../../static/img/apply';
const GetOftenMenuByUser = () => {
  // service.enjoyShowLoading('正在查询...');
	let request = {
		url: LoginStore.EnjoyMain,
		data: {
			UniqueKey: "管易通40公共",
			ObjectData: {
				//用于苹果审核特殊处理获取不到用户时默认按0006账号获取this.loginInfo.sUser
				sMkUser: loginInfo.sUser ? loginInfo.sUser : '0006'
			},
			MethodName: "GetOftenMenuByUser",
		},
	};

  let list:any[] = [];
  service.request(request, (res: any) => {
	if (res && res.data && !res.data.HasException) {
		const objectData = res.data.ObjectData;
		if (objectData != null && objectData.length > 0) {
			list = objectData.filter(item => item.c_client_type == 'Mobile').map((i:any, index:number) => ({
				sort: index,
				...i,
				c_start_color: i.c_start_color ? hexToRgbToLinear(i.c_start_color) : 'rgba(1, 126, 255, 0.08)',
				c_menu_img: i.c_menu_img ? `${baseUrl}/${i.c_menu_img}.png` : `${baseUrl}/apply_bg_qtjl.png`,
			}));
		}
	} else {
	  uni.showToast({
		duration: 3500,
		icon: 'none',
		title: res.data.Exception.Message || '',
		mask: true,
      });
    }
    columnList.value = list;
		// service.enjoyHideLoading();
	}, () => {
		// service.enjoyHideLoading();
		console.log('失败')
	});
};


/**
 *  长按菜单处理程序
 */
const longPressTimeout = 1000; // 长按时长，单位毫秒
const isLongPressed = ref(false);
let longPressTimer:any;

const startLongPress = (item:string) => {
  if (longPressTimer) {
    clearTimeout(longPressTimer);
  }
  longPressTimer = setTimeout(() => {
    isLongPressed.value = true;
    longPressHandle(item);
  }, longPressTimeout);
}

const endLongPress = () => {
  if (longPressTimer) {
    clearTimeout(longPressTimer);
    longPressTimer = null;
    isLongPressed.value = false;
  }
}
// 长按事件
const longPressHandle = (value: string) => {
  uni.showModal({
    title: '提示',
    content: '请问要删除当前菜单吗？',
    success: function(res) {
      if (res.confirm) {
        DeleteOftenMenuByUser(value)
      }
    }
  })
}
// 删除常用菜单项
const DeleteOftenMenuByUser = (code: string) => {
  service.enjoyShowLoading('正在删除...');
	let request = {
		url: LoginStore.EnjoyMain,
		data: {
			UniqueKey: "管易通40公共",
			ObjectData: {
        //用于苹果审核特殊处理获取不到用户时默认按0006账号获取this.loginInfo.sUser
        c_userno: loginInfo.sUser ? loginInfo.sUser : '0006',
        c_mdcode: code
      },
			MethodName: "DeleteOftenMenuByUser",
		},
	};

  service.request(request, (res: any) => {
		service.enjoyHideLoading();
		if (res && res.data && !res.data.HasException && res.data.ObjectData) {
			GetOftenMenuByUser();
		} else {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: res.data.Exception.Message || '',
        mask: true,
      });
    }
	}, () => {
		//service.enjoyHideLoading();
		console.log('失败')
	});
};

const onClickAddMenu = () => {
  const extras = {
      IsMult: '否',
      ExtendData: {
        MenuExtendCode: '',
        c_where: 'home',
      },
      Menus: columnList.value,
    }
  uni.navigateTo({
    url: '/pages/SelectorViews/ModelSelection/index?extras='+ JSON.stringify(extras),
  });
};


const onClickMenu = (item: Menu) => {
  if (!isLongPressed.value) {
    let moduleInfo = encodeURIComponent(JSON.stringify(item));
    uni.navigateTo({
      url: `${item.c_md_name}?moduleInfo=${moduleInfo}`
    });
  }
};

onLoad(() => {
  GetOftenMenuByUser();
});

const refreshQueryEvent = () => {
  GetOftenMenuByUser();
};
onMounted(() => {
  eventBus.on('refresh-HomeMenu', refreshQueryEvent)
});


const homeStore = useRefreshStore();
watch(() => homeStore.refreshTrigger, (newVal, oldValue) => {
    console.log('监听的数据刷新了啊!!!!!!!!!!!!!!!!!!!', newVal, oldValue, homeStore.refreshType);
    if (newVal == true && homeStore.refreshType == 'HomeRefresh') {
      GetOftenMenuByUser();
    }
  }
);

const imageError = (item) => {
  item.c_menu_img = '../../../static/img/apply/apply_bg_qtjl.png';
};

onUnmounted(() => {
  eventBus.off('refresh-HomeMenu', refreshQueryEvent);
})
</script>


<style lang="scss" scoped>
  .menu-container {
    padding-top: 28rpx;
    box-align: border-box;
    background-color: #fff;
    border-radius: 20rpx;
    box-sizing: border-box;
    overflow: hidden;
    .grid-item-class {
      padding: 0 1px;
      box-sizing: border-box;
    }
  }
  .title {
    margin-left: 28rpx;
    margin-bottom: 28rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 600;
    font-size: 32rpx;
    color: #000000;
  }
  .grid-item-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .img-box {
      width: 88rpx;
      height: 88rpx;
      border-radius: 32rpx;
    }
    .image {
      width: 64rpx;
      height: 64rpx;
    }
    .last-image {
      width: 100%;
      height: 100%;
    }
    .text {
      padding: 0 10rpx;
      margin-bottom: 7rpx;
      width: 100%;
      height: 66rpx;
      line-height: 33rpx;
      font-size: 24rpx;
      margin-top: 8rpx;
      font-weight: 500;
      text-align: center;
      font-family: PingFangSC, PingFang SC;
    }
    .last-grid-text {
      color: #666666;
      font-weight: 400;
    }
  }
</style>
